﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Application
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Security.Cryptography;
    using System.Windows.Forms;

    using Mews.Application.Properties;
    using Mews.Net.Nntp;
    using Mews.Net.Nntp.Cache;

    /// <summary>The form that allows the selection of a group from a list.</summary>
    internal sealed partial class SelectGroupForm : DoneCancelForm
    {
        private readonly IHost host;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal SelectGroupForm(IHost host)
        {
            this.host = host;
            this.InitializeComponent();
        }

        internal string SelectedGroup
        {
            get { return (string)(this.groupsListBox.SelectedIndex < 0 ? null : this.groupsListBox.SelectedItem); }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="IDisposable.Dispose"/>.</summary>
        protected sealed override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.components != null)
                {
                    this.components.Dispose();
                }
            }

            base.Dispose(disposing);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void OnGoButton_Click(object sender, System.EventArgs e)
        {
            string groupPart =
                string.IsNullOrEmpty(this.groupPartTextBox.Text) ? "*" : "*" + this.groupPartTextBox.Text + "*";

            if ((groupPart.Length < 4) && (MessageBoxHelper.ShowYesNo(
                Resources.GroupNamesDownloadLargeText, Resources.GroupNamesDownloadLargeCaption) != DialogResult.Yes))
            {
                return;
            }

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                using (var connection = new NetworkConnection(this.host.Name, 30000))
                using (var client = new Client(this.host.Name, this.host.Port))
                {
                    if (!string.IsNullOrEmpty(this.host.AccountName))
                    {
                        new AuthInfoCommand(this.host.AccountName, this.host.Password).Execute(client);
                    }

                    using (var response = new ListNewsgroupsCommand(groupPart).Execute(client))
                    {
                        this.groupsListBox.Items.Clear();

                        while (response.MoveNext())
                        {
                            this.groupsListBox.Items.Add(response.Current.Name);
                        }

                        if (this.groupsListBox.Items.Count > 0)
                        {
                            this.groupsListBox.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (NetworkConnectionFailedException ex)
            {
                MessageBoxHelper.ShowError(
                    ConnectionFailedHelper.GetStatusMessage(ex.Status), Resources.GroupNamesDownloadFailedCaption);
            }
            catch (IOException)
            {
                this.ShowError(Resources.ErrorHostUnreachable);
            }
            catch (ServiceUnavailableException)
            {
                this.ShowError(Resources.ErrorServiceUnavailable);
            }
            catch (MissingAuthenticationException)
            {
                this.ShowError(Resources.GroupNamesDownloadFailedAuthenticationMissing);
            }
            catch (AuthenticationFailedException)
            {
                this.ShowError(Resources.ErrorAuthenticationFailed);
            }
            catch (CryptographicException)
            {
                this.ShowError(Resources.DecryptionFailed);
            }
            catch (ClientException ex)
            {
                MessageBoxHelper.ShowError(
                    string.Format(
                        CultureInfo.InvariantCulture, Resources.GroupNamesDownloadFailedFailureUnexpected, ex.Message),
                    Resources.GroupNamesDownloadFailedCaption);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void ShowError(string text)
        {
            MessageBoxHelper.ShowError(
                string.Format(CultureInfo.InvariantCulture, text, this.host.Name),
                Resources.GroupNamesDownloadFailedCaption);
        }
    }
}

